package com.ja.sevice.impl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ja.config.WebsiteStateConfig;
import com.ja.dao.BjlMapper;
import com.ja.dao.BjlMoneyMapper;
import com.ja.dao.UserMapper;
import com.ja.domain.BaccaratBulletin;
import com.ja.domain.Bjl;
import com.ja.domain.BjlMoney;
import com.ja.domain.Bjldata;
import com.ja.domain.Dama;
import com.ja.domain.Damal;
import com.ja.domain.Data;
import com.ja.domain.Liushui;
import com.ja.domain.Lotter;
import com.ja.domain.Records;
import com.ja.domain.User;
import com.ja.domain.Yb;
import com.ja.sevice.BjlService;
import com.ja.util.BjlUtil;
import com.ja.util.DateUtil;

@Service
public class BjlServiceImpl implements BjlService{
	
	@Autowired
	private BjlMapper bjlMapper;
	
	@Autowired
	public UserMapper userMapper;
	
	@Autowired
	private BjlMoneyMapper bjlMoneyMapper;
	public static List<Yb> list1;
	public static List<Yb> list2;
	public static List<Yb> list3;
	public static List<Yb> list4;
	public static List<Yb> list5;
	public static List<Yb> list6;
	
	
	@Override
	public Double Money(Integer userid) {
		return bjlMapper.Money(userid);
	}
	@Override
	public Lotter bjlpl(String name, String cname) {
		return bjlMapper.bjlpl(name, cname);
	}
	@Override
	public int Moneyxg(Double money,Integer id) {
		return bjlMapper.Moneyxg(money, id);
	}
	
	@Override
	// 查询下注记录
	public List<Records> hRecords1(Integer userid) {
		return bjlMapper.hRecords(userid);
	}
	@Override
	public List<BaccaratBulletin> tableNumber() {
		return bjlMapper.tableNumber();
	}
	@Override
	public List<Bjldata> history(Integer tableNumber) {
		return bjlMapper.history(tableNumber);
	}
	
	@Override
	public int addOrderInfo(BjlMoney moneys) {
		if (moneys.getTable_num()=="") {
			return 1;
		}
		return bjlMoneyMapper.addOrderInfo(moneys);
	}
	
	@Override
	public BjlMoney findUserOrderInfo(BjlMoney moneys) {
		return bjlMoneyMapper.findUserOrderInfo(moneys);
	}
	@Override
	public void insertbjl() {
		Data data = bjlMoneyMapper.selectbjl("bjl");
		if(data == null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
			Data d = new Data();
			d.setCname("bjl");
			d.setGameNameInChinese("百家乐");
			d.setLottertime(sdf.format(new Date()));
			d.setNextStopOrderTimeEpoch(sdf.format(new Date()));
			d.setPeriod("20180950");
			d.setNextperiod("20180951");
			d.setLotternumber("08,04,03,10,01,06,07,05,02,09,");
			d.setPaijtime(sdf.format(new Date()));
			d.setTouzhuzt("已结束");
			d.setState("已开奖");
			d.setType(0);
			d.setStatus(1);
			d.setOpenTime(sdf.format(new Date()));
			bjlMoneyMapper.insertbjl(d);
		}
		
	}
	@Override
	public int deletebjl(Integer userid) {
		return bjlMapper.deletebjl(userid);
	}
	@Override
	public int insertBjlData(List<Bjldata> list) {
		return bjlMapper.insertBjlData(list);
	}
	
	/**
	 * 生成百家乐开奖期号和时间
	 * @param num 桌号
	 * @return
	 */
	@Override
	public void ississueNumber(int num){
		System.out.println(num+"------------桌号-------------");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		SimpleDateFormat sdfperiod = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat sdfperiod1 = new SimpleDateFormat("yyyy/MM/dd");
		/***查询当天是否有低1期*/
		Bjldata bjl = bjlMapper.queryBjlData(sdfperiod.format(new Date())+"1",num); //查询今天的数据是否已经生成
		if(bjl == null) {//如果等于null说明没有生成第一期 则要生成第一期
			Calendar calendar = Calendar.getInstance();
			try {
				calendar.setTime(sdf.parse(sdfperiod1.format(new Date())+" 00:00:00"));
			} catch (ParseException e) {e.printStackTrace();}
			List<Bjldata> list = new ArrayList<Bjldata>();
			for(int i = 1;i<3;i++) {
				Bjldata bjldata = new Bjldata();
				bjldata.setIssueNumber(sdfperiod.format(new Date())+i);//每天的第一期
				bjldata.setNextIssueNumber(sdfperiod.format(new Date())+(i+1));//下一期
				bjldata.setOpeningTimeOfTheCurrentAward(sdf.format(calendar.getTime()));//当期开奖时间
				calendar.add(Calendar.MINUTE, +1);
				bjldata.setNextTime(sdf.format(calendar.getTime()));//下期开奖时间
				bjldata.setState(0);
				bjldata.setTableNumber(num);
				list.add(bjldata);
			}
			bjlMapper.insertBjlData(list);
		}
		Bjldata bjls = bjlMapper.queryBjlData(sdfperiod.format(new Date())+"8",num); //查询今天的数据是否已经生成
		if(bjls == null) {
			Date date = new Date();
			List<Bjldata> list = new ArrayList<Bjldata>();
			Calendar calendar = Calendar.getInstance();
			try {
				calendar.setTime(sdf.parse(sdfperiod1.format(date)+" 00:02:00"));
			} catch (ParseException e) {e.printStackTrace();}//当天开奖的第3期
			for(int i = 3;i<=1442;i++) {
				Bjldata bjldata = new Bjldata();
				bjldata.setState(0);//状态设置成未开奖
				bjldata.setTableNumber(num);//桌号
				bjldata.setOpeningTimeOfTheCurrentAward(sdf.format(calendar.getTime()));//当期开奖时间
				calendar.add(Calendar.MINUTE, +1);
				bjldata.setNextTime(sdf.format(calendar.getTime()));//下期开奖时间
				if(i <= 1439) {
					bjldata.setIssueNumber(sdfperiod.format(date)+i);//当期开奖期号
					bjldata.setNextIssueNumber(sdfperiod.format(date)+(i+1));//下期开奖期号
				}else {
					String period = DateUtil.findLatelyDate(1).replaceAll("-", "");
					if(i > 1440) {
						if(i > 1441) {
							bjldata.setIssueNumber(period+"2");//当期开奖期号
							bjldata.setNextIssueNumber(period+"3");//下期开奖期号
						}else {
							bjldata.setIssueNumber(period+"1");//当期开奖期号
							bjldata.setNextIssueNumber(period+"2");//下期开奖期号
						}
					}else {
						bjldata.setIssueNumber(sdfperiod.format(new Date())+i);//当期开奖期号
						bjldata.setNextIssueNumber(period+"1");//下期开奖期号
					}
				}
				list.add(bjldata);
			}
			bjlMapper.insertBjlData(list);
		}
	
	
	
	
	}
	@Override
	public Bjldata NewestData(Integer tableNumber, String nowTime) {
		return bjlMapper.NewestData(tableNumber, nowTime);
	}
	/**
	 * 每各一分钟走一次，给百家乐派奖
	 * 百家乐一号桌
	 */
	@Override
	public void table1() {
		Bjldata data1;
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		data1 = bjlMapper.NewestData(1, sdf.format(new Date()));
		while(true) {
			try {
				//System.err.println("已经开到----1-------"+data1.getIssueNumber());
				//下期开奖时间
				Long endTime = sdf.parse(data1.getOpeningTimeOfTheCurrentAward()).getTime();
				//当前系统时间
				Long startTime = sdf.parse(sdf.format(new Date())).getTime();
				Long time = (endTime - startTime) - 14000;
				if(time > 0) {
					Thread.sleep(time);
				}
				Lottery(bjlMapper.queryBjlDatas(data1.getIssueNumber(), data1.getTableNumber()));//开奖
				//查询下期开奖数据
				data1 = bjlMapper.queryBjlData(data1.getNextIssueNumber(), data1.getTableNumber());
				//清空集合里面的假硬币
				list1 = null;
			} catch (ParseException | InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	@Override
	public void table2() {
		Bjldata data2;
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		data2 = bjlMapper.NewestData(2, sdf.format(new Date()));
		while(true) {
			try {
				//System.err.println("已经开到----2-------"+data2.getIssueNumber());
				//下期开奖时间
				Long endTime = sdf.parse(data2.getOpeningTimeOfTheCurrentAward()).getTime();
				//当前系统时间
				Long startTime = sdf.parse(sdf.format(new Date())).getTime();
				Long time = (endTime - startTime) - 14000;
				if(time > 0) {
					Thread.sleep(time);
				}
				Lottery(bjlMapper.queryBjlDatas(data2.getIssueNumber(), data2.getTableNumber()));//开奖
				//查询下期开奖数据
				data2 = bjlMapper.queryBjlData(data2.getNextIssueNumber(), data2.getTableNumber());
				//清空集合里面的假硬币
				list2 = null;
			} catch (ParseException | InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
	@Override
	public void table3() {
		Bjldata data3;
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		data3 = bjlMapper.NewestData(3, sdf.format(new Date()));
		while(true) {
			try {
				//System.err.println("已经开到------3-----"+data3.getIssueNumber());
				//下期开奖时间
				Long endTime = sdf.parse(data3.getOpeningTimeOfTheCurrentAward()).getTime();
				//当前系统时间
				Long startTime = sdf.parse(sdf.format(new Date())).getTime();
				Long time = (endTime - startTime) - 14000;
				if(time > 0) {
					Thread.sleep(time);
				}
				//掉开奖方法
				Lottery(bjlMapper.queryBjlDatas(data3.getIssueNumber(), data3.getTableNumber()));//开奖
				//查询下期开奖数据
				data3 = bjlMapper.queryBjlData(data3.getNextIssueNumber(), data3.getTableNumber());
				//清空集合里面的假硬币
				list3 = null;
			} catch (ParseException | InterruptedException e) {
				e.printStackTrace();
			}
		
			
		}
		
	}
	@Override
	public void table4() {
		Bjldata data4;
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		data4 = bjlMapper.NewestData(4, sdf.format(new Date()));
		while(true) {
			try {
				//System.err.println("已经开到-----4------"+data4.getIssueNumber());
				//下期开奖时间
				Long endTime = sdf.parse(data4.getOpeningTimeOfTheCurrentAward()).getTime();
				//当前系统时间
				Long startTime = sdf.parse(sdf.format(new Date())).getTime();
				Long time = (endTime - startTime) - 14000;
				if(time > 0) {
					Thread.sleep(time);
				}
				Lottery(bjlMapper.queryBjlDatas(data4.getIssueNumber(), data4.getTableNumber()));//开奖
				//查询下期开奖数据
				data4 = bjlMapper.queryBjlData(data4.getNextIssueNumber(), data4.getTableNumber());
				//清空集合里面的假硬币
				list4 = null;
			} catch (ParseException | InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
	@Override
	public void table5() {
		Bjldata data5;
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		data5 = bjlMapper.NewestData(5, sdf.format(new Date()));
		while(true) {
			try {
				//System.err.println("已经开到------5-----"+data5.getIssueNumber());
				//下期开奖时间
				Long endTime = sdf.parse(data5.getOpeningTimeOfTheCurrentAward()).getTime();
				//当前系统时间
				Long startTime = sdf.parse(sdf.format(new Date())).getTime();
				Long time = (endTime - startTime) - 14000;
				if(time > 0) {
					Thread.sleep(time);
				}
				Lottery(bjlMapper.queryBjlDatas(data5.getIssueNumber(), data5.getTableNumber()));//开奖
				//查询下期开奖数据
				data5 = bjlMapper.queryBjlData(data5.getNextIssueNumber(), data5.getTableNumber());
				//清空集合里面的假硬币
				list5 = null;
			} catch (ParseException | InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	@Override
	public void table6() {
		Bjldata data6;
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		data6 = bjlMapper.NewestData(6, sdf.format(new Date()));
		while(true) {
			try {
				//System.err.println("已经开到------6-----"+data6.getIssueNumber());
				//下期开奖时间
				Long endTime = sdf.parse(data6.getOpeningTimeOfTheCurrentAward()).getTime();
				//当前系统时间
				Long startTime = sdf.parse(sdf.format(new Date())).getTime();
				Long time = (endTime - startTime) - 14000;
				if(time > 0) {
					Thread.sleep(time);
				}
				Lottery(bjlMapper.queryBjlDatas(data6.getIssueNumber(), data6.getTableNumber()));//开奖
				//查询下期开奖数据6
				data6 = bjlMapper.queryBjlData(data6.getNextIssueNumber(), data6.getTableNumber());
				//清空集合里面的假硬币
				list6 = null;
			} catch (ParseException | InterruptedException e) {
				e.printStackTrace();
			}
		
		}
		
	}
	/**
	 * 处理下注信息
	 */
	@Override
	public int bjlBets(Bjl b,User user) {
		System.out.println(WebsiteStateConfig.getLotter("bjl").getState()+"百家乐的状态");
		if(WebsiteStateConfig.getLotter("bjl").getState() != 1) {
			return 7;//百家乐已经关闭不能进行投注
		}
		if(b.getTotalBet() == null || b.getTotalBet() <= 0) {
			//总金额不能为null&&不能为小于0
			return 5;
		}
		if(b.getAmountOfMoney() == null) {
			b.setAmountOfMoney(0.00);
		}
		if(b.getCashDownAmount() == null) {
			b.setCashDownAmount(0.00);
		}
		if(b.getCashPairDownAmount() == null) {
			b.setCashPairDownAmount(0.00);
		}
		if(b.getZhuangdusBetOnTheAmount() == null) {
			b.setZhuangdusBetOnTheAmount(0.00);
		}
		if(b.getAndTheAmountOfTheBet() == null) {
			b.setAndTheAmountOfTheBet(0.00);
		}
		if(b.getLargeBetAmount() == null) {
			b.setLargeBetAmount(0.00);
		}
		if(b.getSmallBetAmount() == null) {
			b.setSmallBetAmount(0.00);
		}
		if(b.getPerfectPairAmount() == null) {
			b.setPerfectPairAmount(0.00);
		}
		if(b.getArbitraryPairAmount() == null) {
			b.setArbitraryPairAmount(0.00);
		}
		double total = b.getArbitraryPairAmount()+b.getPerfectPairAmount()+b.getSmallBetAmount()+b.getLargeBetAmount()+b.getAndTheAmountOfTheBet()+b.getZhuangdusBetOnTheAmount()+b.getCashPairDownAmount()+b.getCashDownAmount() +b.getAmountOfMoney();
		double total1 = b.getTotalBet();
		if(total1 != total) {
			//传入金额和总金额不符合
			return 6;
		}
		//查询用户金额
		Double money = bjlMapper.Money(user.getId());
		System.out.println(b.getIssueNumber()+"-----下注期号----------下注桌号-----"+ b.getTableNumber());
		Bjldata data = bjlMapper.queryBjlDatas(b.getIssueNumber(), b.getTableNumber());
		//System.out.println(data.toString());
		if(data.getState() == 1) {
			//当期已开奖
			return 3;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Long endTime;
		try {
			endTime = sdf.parse(data.getOpeningTimeOfTheCurrentAward()).getTime();
			//当前系统时间
			Long startTime = sdf.parse(sdf.format(new Date())).getTime();
			Long time = (endTime - startTime) - 15000;
			if(time < 0) {
				return 3;//当期已开奖
			}
		} catch (ParseException e) {}
		if(money >= b.getTotalBet()) {
			Double money1 = money-b.getTotalBet();
			int num = bjlMapper.Moneyxg(money1, user.getId());
			if(num == 1) {
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
				b.setState(0); //设置为未开奖
				b.setStatus(2);//设置状态为  未开奖
				b.setUserstate(user.getState());
				b.setName(user.getName());
				b.setUserid(user.getId());
				b.setBettingtime(sdf.format(new Date()));
				int sum = bjlMapper.insertBets(b);
				//流水表
				Liushui liushui = new Liushui();
				liushui.setHuiyuanzh(user.getName());//会员账号
				liushui.setBdtype("百家乐投注");//变动类型
				liushui.setBdqjine(money);//变动前金额
				liushui.setBdjine(b.getTotalBet());//变动金额
				liushui.setBdhjine(money1);//变动后余额
				liushui.setCreatetime(sdf1.format(new Date()));//变动时间
				liushui.setOrdernum("B"+sdf2.format(new Date()));//订单号
				liushui.setCname("百家乐");//彩种名称
				liushui.setPeriod(b.getIssueNumber());//期号
				liushui.setState(false);//收入还是支出   true 收入  false 支出
				liushui.setUserid(user.getId());
				bjlMapper.addWater(liushui);
				if(user.getState() == 1) {
					//添加打码记录
					Dama dama = new Dama();
					dama.setHuiyuanzh(user.getName());//会员账号	
					dama.setBdtype("百家乐投注");//变动类型
					dama.setBdcount(b.getTotalBet());//变动打码量
					dama.setCreatetime(sdf1.format(new Date()));//创建时间
					dama.setCzname("系统自动");//操作人员
					dama.setBeizhu("百家乐投注");
					dama.setUserid(user.getId());//会员id
					bjlMapper.addCode(dama);
					//添加平台用户打码量统计表
					Damal al = bjlMapper.queryCode(user.getId());
					if(al != null) {
						//修改
						Damal d = new Damal();
						d.setHuiyuanzh(user.getName());//会员账号
						d.setDamaliang(al.getDamaliang()+b.getTotalBet());//会员打码量 如果中途发生图款则减掉这个字段的打码量
						d.setCreatetime(sdf1.format(new Date()));//创建时间
						d.setUserid(user.getId());//用户id
						bjlMapper.modifyUserCodings(d);
					}else {
						//创建
						Damal d = new Damal();
						d.setHuiyuanzh(user.getName());//会员账号
						d.setDamaliang(b.getTotalBet());//会员打码量 如果中途发生图款则减掉这个字段的打码量
						d.setCreatetime(sdf1.format(new Date()));//创建时间
						d.setUserid(user.getId());//用户id
						d.setState(1);//开关
						bjlMapper.newCode(d);
					}
				}
				return sum;//1 下注成功
			}else {
				return 0;//下注失败
			}
		}else {
			return 2;//余额不足
		}
	}
	/**
	 * 开奖
	 * 查询用户下注数据进行开奖
	 */
	@Override
	public int Lottery(Bjldata data) {
		/**
		 * rebate1 庄家的赔率
		 * rebate2 闲家的赔率
		 * rebate3闲对的赔率
		 * rebate4庄对的赔率
		 * rebate5和局的赔率
		 * rebate6大的赔率
		 * rebate7小的赔率
		 * rebate8完美对子的赔率
		 * rebate9任意对子的赔率
		 */
		Thread th = new Thread() {
			@Override
			public void run() {
				Bjldata bjldata = null;
				BjlUtil bjl = new BjlUtil();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				/**获取赔率*/
				Lotter lotter = bjlMapper.bjlpl("百家乐", "bjl");
				/**查询用户下注信息*/
				List<Bjl> list = bjlMapper.queryBetInformation(data.getIssueNumber(), data.getTableNumber());
				/**获取百家乐公共设置数据*/
				BaccaratBulletin baccaratBulletin = bjlMapper.bfb(data.getTableNumber());
				baccaratBulletin.setLotteryTimes(baccaratBulletin.getLotteryTimes()+1);//开奖次数加1 当大于10的时候 设置为0
				if(baccaratBulletin.getLotteryTimes() >= 11) { //当开奖次数大于10的时候  设置为0
					baccaratBulletin.setLotteryTimes(0); //设置成0
				}
				if(data.getState() != 2) { //等于2时说明 后台已经预设开奖数据了
					/**
					 * 获取控制数组
					 * 当开启控制的时候则进入 没有开启控制的时候 则不进入
					 */
					if(baccaratBulletin.getPercentage() > 0) {//判断是否是开启控制状态
						if(baccaratBulletin.getControl() == null || "".equals(baccaratBulletin.getControl())) { //判断上次控制到第几次了 如果为null或者为空串 则进来生成控制次数
							Set<Integer> set   = bjl.control(baccaratBulletin.getPercentage());//根据控制次数生成到那一期开启控制
							StringBuffer sb = new StringBuffer();
							for(Integer s : set) {
								sb.append(s+",");
							}
							bjlMapper.updateControl(sb.toString(), data.getTableNumber());
							baccaratBulletin.setControl(sb.toString());
						}
						double zhuang = 0.00;
						double xian = 0.00;
						for(Bjl b : list) {  //计算庄闲 看哪家下注的钱多
							if(b.getUserstate() == 1) {//正规玩家才统计
								if(b.getAmountOfMoney() != null) {
									zhuang +=b.getAmountOfMoney();
								}
								if(b.getCashDownAmount() != null) {
									xian +=b.getCashDownAmount();
								}
							}
						}
						StringBuffer sbr = new StringBuffer();
						String[] str = baccaratBulletin.getControl().split(",");  //获取开奖控制次数  劈开把次数到winner里面去
						//判断钱少的一家赢
						if(zhuang > xian) {
							/**要闲家赢*/
							 bjldata = bjl.winner(baccaratBulletin.getLotteryTimes(),new Integer(str[0]),0);
						}else if(xian > zhuang) {
							 /**要庄家赢 开奖状态  0-闲家赢 1-庄家赢  2-和局*/
							 bjldata = bjl.winner(baccaratBulletin.getLotteryTimes(),new Integer(str[0]),1);
						}else{
							/**随便开一个*/
							 bjldata = new BjlUtil().bjlData();
						}
						for(int i = 1;i<str.length;i++) {
							sbr.append(str[i]+",");
						}
						bjlMapper.updateControl(sbr.toString(), data.getTableNumber());
					}else {
						/**生成开奖号*/
						bjldata = new BjlUtil().bjlData();
					}
				}else {
					bjldata = data;//把后台预设的开奖数据赋值给 bjldata
				}
				
				/**计算钱*/
				for(Bjl b : list) {
					if(b.getState() == 0) {
						Bjl bj = new Bjl();
						//User u = userMapper.checkUser(b.getName());
						
						/**赢家   0-闲家赢 1-庄家赢  2-和局*/
						if(bjldata.getWinner() == 0) {
							/**闲家下注金额*/
							bj.setWinningAmount(b.getCashDownAmount()*new Double(lotter.getRebate2()));
						}else if(bjldata.getWinner() == 1) {
							/**庄家下注金额*/
							bj.setWinningAmount(b.getAmountOfMoney()*new Double(lotter.getRebate1()));
						}else if(bjldata.getWinner() == 2) {
							/**和局下注金额  并且添加退款流水*/
							bj.setWinningAmount(b.getAndTheAmountOfTheBet()*new Double(lotter.getRebate5()));
							/**添加退款流水*/
							double amountOfMoney = b.getAmountOfMoney();
							double cashDownAmount = b.getCashDownAmount();
							if(amountOfMoney+cashDownAmount > 0) {
								Double money = bjlMapper.Money(b.getUserid());
								bjlMapper.Moneyxg(amountOfMoney+cashDownAmount+money, b.getUserid());//退钱
								Liushui liushui = new Liushui();
								liushui.setHuiyuanzh(b.getName());//会员账号
								liushui.setBdtype("百家乐和局退款");//变动类型
								liushui.setBdqjine(money);//变动前金额
								liushui.setBdjine(b.getAmountOfMoney()+b.getCashDownAmount());//变动金额
								liushui.setBdhjine(b.getAmountOfMoney()+b.getCashDownAmount()+money);//变动后余额
								liushui.setCreatetime(sdf1.format(new Date()));//变动时间
								//liushui.setOrdernum("B"+sdf2.format(new Date()));//订单号
								liushui.setCname("百家乐");//彩种名称
								liushui.setPeriod(b.getIssueNumber());//期号
								liushui.setState(true);//收入还是支出   true 收入  false 支出
								liushui.setCzname("系统自动");
								liushui.setUserid(b.getUserid());
								bjlMapper.addWater(liushui);
							}
						}
						/**闲对 0-没有闲对 1-有闲对*/
						if(bjldata.getIdleTime() == 1) {
							/**闲对下注金额*/
							bj.setWinningAmount((b.getCashPairDownAmount()*
									new Double(lotter.getRebate3()))+bj.getWinningAmount());
						}
						/**庄对 0-没有庄对 1-有庄对*/
						if(bjldata.getZhuangPairs() == 1) {
							/**庄对下注金额*/
							bj.setWinningAmount(b.getZhuangdusBetOnTheAmount()*
									new Double(lotter.getRebate4())+bj.getWinningAmount());
						}
						/**完美对子*/
						if(bjldata.getPerfectPair() == 1) {
							/**完美对子*/
							bj.setWinningAmount(b.getPerfectPairAmount()*
									new Double(lotter.getRebate8())+bj.getWinningAmount());
						}
						/**任意对子*/
						if(bjldata.getArbitraryPairs() == 1) {
							/**有任意对子*/
							bj.setWinningAmount(b.getArbitraryPairAmount()*
									new Double(lotter.getRebate9())+bj.getWinningAmount());
						}
						/**大、小*/
						if(bjldata.getSize() == 1) {
							/**大*/
							bj.setWinningAmount(b.getLargeBetAmount()*
									new Double(lotter.getRebate6())+bj.getWinningAmount());
						}else {
							/**小*/
							bj.setWinningAmount(b.getSmallBetAmount()*
									new Double(lotter.getRebate7())+bj.getWinningAmount());
						}
						bj.setState(1);
						bj.setStatus(2);
						if(bj.getWinningAmount() > 0) {
							Double money = bjlMapper.Money(b.getUserid());
							/**结算钱*/
							bjlMapper.Moneyxg(bj.getWinningAmount()+money, b.getUserid());
							bj.setStatus(1);
							/**添加流水*/
							Liushui liushui = new Liushui();
							liushui.setHuiyuanzh(b.getName());//会员账号
							liushui.setBdtype("百家乐派奖");//变动类型
							liushui.setBdqjine(money);//变动前金额
							liushui.setBdjine(bj.getWinningAmount());//变动金额
							liushui.setBdhjine(bj.getWinningAmount()+money);//变动后余额
							liushui.setCreatetime(sdf1.format(new Date()));//变动时间
							liushui.setOrdernum("-");//订单号
							liushui.setCname("百家乐");//彩种名称
							liushui.setPeriod(b.getIssueNumber());//期号
							liushui.setState(true);//收入还是支出   true 收入  false 支出
							liushui.setCzname("系统自动");
							liushui.setUserid(b.getUserid());
							bjlMapper.addWater(liushui);
						}
						//更新打码
						if(b.getUserstate() == 1) {//正规玩家才统计打码
							Damal al = bjlMapper.queryCode(b.getUserid());
							System.out.println(al.toString()+"查询出来的记录");
							Damal d = new Damal();
							d.setHuiyuanzh(b.getName());//会员账号
							d.setNew_damaliang(al.getNew_damaliang()+b.getTotalBet());//会员打码量
							d.setCreatetime(sdf1.format(new Date()));//创建时间
							d.setUserid(b.getUserid());//用户id
							bjlMapper.modifyUserCoding(d);
						}
						bj.setLeisureHomePoints(bjldata.getLeisureHomePoints());//闲家最终点数
						bj.setFrontPointsofIdleReplacementCards(bjldata.getFrontPointsofIdleReplacementCards());//闲家补牌前点数
						bj.setLeisureCard(bjldata.getLeisureCard()); //闲家补牌
						bj.setLeisure2(bjldata.getLeisure2());//闲家第二张牌
						bj.setLeisure1(bjldata.getLeisure1());//闲家第一张牌
						bj.setMakerSFinalPoints(bjldata.getMakerSFinalPoints());//庄家最终点数
						bj.setFrontPointsOfZhuangshi(bjldata.getFrontPointsOfZhuangshi());//庄家补牌前点数
						bj.setDealerCard(bjldata.getDealerCard());//庄家补牌
						bj.setZhuang2(bjldata.getZhuang2());//庄家第二张牌
						bj.setZhuang1(bjldata.getZhuang1());//庄家第一张牌
						bj.setWinner(bjldata.getWinner());//赢家
						bj.setIdleTime(bjldata.getIdleTime());//闲对 0-没有闲对 1-有闲对
						bj.setZhuangPairs(bjldata.getZhuangPairs());// 庄对  0- 没有庄对 1-有庄对
						bj.setPerfectPair(bjldata.getPerfectPair());//完美对子
						bj.setSize(bjldata.getSize());//大小 0-小  1-大
						bj.setArbitraryPairs(bjldata.getArbitraryPairs());//任意对子 0-没有任意对子  1有任意对子',
						bj.setId(b.getId());
						/**更新用户下注信息*/
						bjlMapper.modifyUserNoteInformation(bj);
					}
				}
				/**更新 已经开到了第几次了*/
				bjlMapper.lotteryTimes(baccaratBulletin.getLotteryTimes(), data.getTableNumber());
				/**更新开奖状态*/
				bjldata.setState(1);
				bjldata.setTime(sdf.format(new Date()));
				bjldata.setTableNumber(data.getTableNumber());
				bjldata.setIssueNumber(data.getIssueNumber());
				if(data.getState() == 2) {
					bjlMapper.updataBjlDatas(bjldata);//后台已经填写数据 只需要更新开奖状态和开奖时间即可
				}else { 
					bjlMapper.updataBjlData(bjldata); //更新开奖数据
				}
			}
		};
		th.start();
		return 1;
	}
	
	/**
	 * 开启百家乐
	 */
	@Override
	public void open() {
		Thread t1 = new Thread() {
			@Override
			public void run() {
				table1();
			}
		};
		Thread t2 = new Thread() {
			@Override
			public void run() {
				table2();
			}
		};
		Thread t3 = new Thread() {
			@Override
			public void run() {
				table3();
			}
		};
		Thread t4 = new Thread() {
			@Override
			public void run() {
				table4();
			}
		};
		Thread t5 = new Thread() {
			@Override
			public void run() {
				table5();
			}
		};
		Thread t6 = new Thread() {
			@Override
			public void run() {
				table6();
			}
		};
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
		t6.start();
	}
	/**
	 * 定时任务，每天00:00:00定时生成百家乐开奖数据
	 */
	@Override
	public void timingTask() {
		 ississueNumber(1);
	     ississueNumber(2);
	     ississueNumber(3);
	     ississueNumber(4);
	     ississueNumber(5);
	     ississueNumber(6);
		//得到时间类
        Calendar date = Calendar.getInstance();
        //设置时间为 xx-xx-xx 00:00:00
        date.set(date.get(Calendar.YEAR), date.get(Calendar.MONTH), date.get(Calendar.DATE), 0, 0, 0);
        //一天的毫秒数
        long daySpan = 24 * 60 * 60 * 1000;
        //得到定时器实例
        Timer t = new Timer();
        //使用匿名内方式进行方法覆盖
		Calendar cal = Calendar.getInstance();
	    cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + 1);
	    cal.set(Calendar.HOUR_OF_DAY, 0);
	    cal.set(Calendar.MINUTE, 0);
	    cal.set(Calendar.SECOND, 0);
	    cal.set(Calendar.MILLISECOND, 0);
	    Integer diff = (int) (cal.getTimeInMillis() - System.currentTimeMillis());
        t.schedule(new TimerTask() {
            public void run() {
                //run中填写定时器主要执行的代码块
                ississueNumber(1);
                ississueNumber(2);
                ississueNumber(3);
                ississueNumber(4);
                ississueNumber(5);
                ississueNumber(6);
            }
        }, diff, daySpan); //daySpan是一天的毫秒数，也是执行间隔  
	}
	/**
	 * 查询百家乐开奖数据
	 */
	@Override
	public Bjldata bjlLotter(Bjl b) {
		return bjlMapper.QueryTheLatestPrizeOpeningData(b.getTableNumber());
	}
	@Override
	public List<Bjldata> bjlRoom() {
		List<Bjldata> list = new ArrayList<Bjldata>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		for(int i = 1;i<=6;i++) {
			list.add(bjlMapper.NewestData(i, sdf.format(new Date())));
		}
		return list;
	}
	/**
	 * 根据期号 桌号查询开机数据
	 */
	@Override
	public Bjldata takeAwayTheAwardData(Bjl b) {
		return bjlMapper.takeAwayTheAwardData(b);
	}
	@Override
	public List<Yb> coin(Yb data,Integer tableNumber) {
		if(tableNumber == 1) {
			if(list1 != null) {
				return list1;
			}
			String[] str = {"5","5","5","5","5","5","5","5","5","5",
					"10", "10", "10", "10", "10", "10",
					"20", "20", "20", "20",
					"50","50","50", 
					"200",};
			list1 = coins(data,str);
			return list1;
		}else if(tableNumber == 2){
			if(list2 != null) {
				return list2;
			}
			String[] str = { "50","50","50","50","50","50","50","50","50","50","50",
					"100", "100", "100", "100", "100", "100", "100", "100",
					"500", "500", "500", "500", "500",
					"1000", "1000",
					"5000" };
			list2 = coins(data,str);
			return list2;
		}else if(tableNumber == 3) {
			if(list3 != null) {
				return list3;
			}
			String[] str = { "100", "100","100","100","100","100","100","100","100","100","100",
					"200", "200","200","200","200","200","200","200",
					"500", "500","500","500","500",
					"1000", "1000","5000" };
			list3 = coins(data,str);
			return list3;
		}else if(tableNumber == 4) {
			if(list4 != null) {
				return list4;
			}
			String[] str = { "100", "100","100","100","100","100","100","100","100","100","100","1000","1000",
					"1000","1000","1000","1000","1000","1000","1000", 
					"5000","5000","5000","5000","5000", 
					"10000","10000", "50000" };
			list4 = coins(data,str);
			return list4;
		}else if(tableNumber == 5) {
			if(list5 != null) {
				return list5;
			}
			String[] str = { "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", 
					"2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", 
					"5000","5000","5000","5000","5000",
					"10000", "10000","50000" };
			list5 = coins(data,str);
			return list5;
		}else if(tableNumber == 6){
			if(list6 != null) {
				return list6;
			}
			String[] str = { "1000","1000","1000","1000","1000","1000","1000","1000","1000","1000","1000", 
					"2000","2000","2000","2000","2000","2000","2000","2000", 
					"5000","5000","5000","5000","5000",
					"10000","10000", "50000" };
			list6 = coins(data,str);
			return list6;
		}
		return null;
	}
	public List<Yb> coins(Yb data,String[] str){
		List<Yb> list = new ArrayList<Yb>();
		String[] str1 = { "xiandui", "he", "zhuangdui", "xian", "xian","xian","xian","xian","xian","zhuang","zhuang","zhuang","zhuang","zhuang","zhuang" };
		Random r = new Random();
		for (int i = 0; i < (int) (10 + Math.random() * (80 - 1 + 1)); i++) {
			Yb yb = new Yb();
			yb.setDs(str[r.nextInt(str.length)]);
			yb.setFq1(str1[r.nextInt(str1.length)]);
			yb.setSj((int) (2 + Math.random() * (27 - 1 + 1)) + "");
			for (int j = 0; j < data.getFq().length; j++) {
				if (yb.getFq1().equals(data.getFq()[j])) {
					yb.setLeft1((int) (0 + Math.random() * (data.getLeft()[j] - 1 + 1)));
					yb.setTop1((int) (0 + Math.random() * (data.getTop()[j] - 1 + 1)));
				}
			}
			list.add(yb);
		}
		return list;
	}
	/***
	 * 用户下注以及中奖的金额信息
	 * @param table_num 桌号
	 * @param period 期号
	 * @param session session对象
	 * @return
	 */
	@Override
	public String findUserMoneyInfo(Integer userid, String tableNumber, String issueNumber) {
		List<Bjl> bjl = bjlMapper.findUserMoneyInfo(userid, tableNumber, issueNumber);
		String message = "";
		if (bjl.size() < 1) {
			return "0";
		}
		//中奖总额
		Double money = 0.00;
		//下注金额
		Double money1 = 0.00;
		for(Bjl b : bjl) {
			//System.out.println(b.toString());
			money1+= b.getTotalBet();
			money+=b.getWinningAmount();
			//System.out.println(money1+"money1当期下注金额------");
		}
		//System.out.println(money1+"money1当期下注金额");
		String str = "";
		String lotter_money = "";
		if ((money-money1) < 0) {
			str = "亏损";
			lotter_money = String.valueOf(money-money1);
		} else {
			str = "盈利";
			lotter_money = String.valueOf(money-money1);
		}
		message = "本期下注" + money1 + "元<br>" + str + lotter_money + "元!";
		return message;
	}
	@Override
	public List<Bjldata> bjlkaijiangjilu(Integer tableNumber) {
		return bjlMapper.bjlkaijiangjilu(tableNumber);
	}
	@Override
	public List<Bjldata> findTrendBjl(String time, Integer tableNumber,String issueNumber) {
		return bjlMapper.findTrendBjl(time, tableNumber,issueNumber);
	}
	@Override
	public Bjl bettingRecord(String name,Integer id) {
		return bjlMapper.bettingRecord(name, id);
	}
}
